package com.ccepc.algmanage.scheduled;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ccepc.algmanage.service.DeployInfoService;
import com.ccepc.algmanage.service.IdentificationRecordService;
import com.ccepc.algmanage.service.PushRuleService;
import com.ccepc.demo.api.entity.DeployInfo;
import com.ccepc.demo.api.entity.IdentificationRecord;
import com.ccepc.demo.api.entity.PushRule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 推送消息定时任务
 */
@Service
@Slf4j
public class PushMessageScheduledJob {

    @Resource
    private PushRuleService pushRuleService;

    @Resource
    private DeployInfoService deployInfoService;

    @Resource
    private PushRuleJud pushRuleJud;

    @Resource
    private IdentificationRecordService identificationRecordService;

    @Scheduled(fixedRate = 60000) // 每分钟触发一次
    public void pushMsgTask() {
        //1、遍历推送规则
        List<PushRule> pushRules = pushRuleService.list();
        //2、每一条推送规则查到对应的算法id和推送人
        for (PushRule pushRule:pushRules){
            List<DeployInfo> deployInfos = deployInfoService.list(
                    new LambdaQueryWrapper<DeployInfo>()
                            .eq(DeployInfo::getPushruleId, pushRule.getId())
            );
            for (DeployInfo deployInfo:deployInfos){
                String pushmanId = deployInfo.getPushmanId();
                Integer algorimId = deployInfo.getAlgorimId();
                List<IdentificationRecord> records = identificationRecordService.list(
                        new LambdaQueryWrapper<IdentificationRecord>()
                                .eq(IdentificationRecord::getAlgorimId, algorimId)
                                .eq(pushRule.getOnlyOnce() == 1, IdentificationRecord::getIsPush,0)
                                .eq(IdentificationRecord::getIsHandle, 0)
                );
                //3、一一对比推送规则，判断推送规则是否成立，满足条件推送，不行就继续重复2
                records.forEach(record ->{
                    pushRuleJud.checkAlarm(record, pushRule, pushmanId);
                });
            }
        }
    }
}
